package com.lenovo.translatetext.ui.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.lenovo.translatetext.R;
import com.lenovo.translatetext.api.ApiRetrofit;
import com.lenovo.translatetext.entity.LastPassResult;
import com.lenovo.translatetext.entity.TranslatedInfo;
import com.lenovo.translatetext.utils.FileUtils;
import com.lenovo.translatetext.utils.MD5;
import com.lenovo.translatetext.utils.NgramUtils;
import com.lenovo.translatetext.utils.Utils;
import okhttp3.ResponseBody;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.lenovo.translatetext.Constant.BAIDU_APP_ID;
import static com.lenovo.translatetext.Constant.KEY;

public class LastPassActivity extends AppCompatActivity {
    private static final String TAG = LastPassActivity.class.getSimpleName();
    @BindView(R.id.result)
    EditText output;
    List<LastPassResult> results = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_last_pass);
        ButterKnife.bind(this);
        TranslateTask task = new TranslateTask();
        task.execute();
    }

    /**
     * 读取解析失败的Excel表数据
     *
     * @return
     */
    private List<LastPassResult> readFailExcel(String filePath) throws IOException {
        List<LastPassResult> results = new ArrayList<>();
        InputStream stream = FileUtils.getAssetResourcesFileInputStream("fail.xls");
        HSSFWorkbook workbook = new HSSFWorkbook(stream);
        HSSFSheet sheet = workbook.getSheetAt(0);
        int rowsCount = sheet.getPhysicalNumberOfRows();
        Log.d(TAG, "readFailExcel: rowsCount--->" + rowsCount);
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        LastPassResult lastPassResult = null;
        for (int r = 1; r < rowsCount; r++) {
            Row row = sheet.getRow(r);
            lastPassResult = new LastPassResult();
            lastPassResult.setCountryCode(FileUtils.getCellAsString(row, 0, formulaEvaluator));
            lastPassResult.setOriginalText(FileUtils.getCellAsString(row, 1, formulaEvaluator));
            lastPassResult.setCompareText(FileUtils.getCellAsString(row, 2, formulaEvaluator));
            lastPassResult.setCodeResult(FileUtils.getCellAsString(row, 3, formulaEvaluator));
            lastPassResult.setCodeRemark(FileUtils.getCellAsString(row, 4, formulaEvaluator));
            results.add(lastPassResult);
        }
        Log.d(TAG, "readFailExcel: Results--->" + results.toString());
        return results;
    }

    private boolean ipIsForbidden = false;

    private List<LastPassResult> translateByGoogle(List<LastPassResult> results) {
//        String salt = null;
//        String sign = null;
        for (LastPassResult result : results) {
//            salt = String.valueOf(new Random().nextInt(10000));
//            sign = MD5.getMD5(BAIDU_APP_ID + result.getCompareText() + salt + KEY);
            if (!ipIsForbidden) {
//                ApiRetrofit.getBaiduTranslateApi()
//                        .getTranslatedText(result.getCompareText(), "auto", "en", BAIDU_APP_ID, salt, sign)
//                        .enqueue(new Callback<TranslatedInfo>() {
//                            @Override
//                            public void onResponse(Call<TranslatedInfo> call, Response<TranslatedInfo> response) {
//                                TranslatedInfo info = response.body();
//                                Log.d(TAG, "onResponse: ResponseBody--->" + info.toString());
//                                String errorCode = info.getError_code();
//                                if (errorCode == null) {
//                                    //打印到界面上
//                                    result.setTranslatedText(info.getTrans_result().get(0).getDst());
//                                    if (result.getTranslatedText().toLowerCase().equals(result.getOriginalText()
// .toLowerCase())) {
//                                        result.setTranslateResult("Pass");
//                                    } else {
//                                        result.setTranslateResult("Fail");
//                                    }
//                                } else {
//                                    ipIsForbidden = true;
//                                }
//                            }
//
//                            @Override
//                            public void onFailure(Call<TranslatedInfo> call, Throwable t) {
//                                Log.d(TAG, "onFailure: " + t.toString());
//                            }
//                        });
            ApiRetrofit.getGoogleTranslateApi()
                    .translateGoogle(result.getCompareText(), result.getCountryCode(), "en")
                    .enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            String responseText = null;
                            try {
                                if (response.code() !=200) {
                                    ipIsForbidden = true;
                                    return;
                                }
                                responseText = response.body().string();
                                List<String> patterns = Utils.parseGoogleResult(responseText);
                                Log.d(TAG, "onResponse: Results After Parse--->" + patterns.toString());
                                result.setTranslatedText(patterns.get(0));
                                if (patterns.get(0).trim().toLowerCase().equals(result.getOriginalText().trim()
                                        .toLowerCase())) {
                                    result.setTranslateResult("Pass");
                                } else {
                                    result.setTranslateResult("Fail");
                                }
                                result.setDistance(NgramUtils.getDistance(result.getTranslatedText(),result.getOriginalText()));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Log.d(TAG, "onFailure: " + t.toString());
                        }
                    });
            //防止短时间内多次请求导致被封ip
            SystemClock.sleep(1000 * 60);
            } else {
                return results;
            }
        }
        Log.d(TAG, "translateByGoogle: Results--->" + results.toString());
        return results;
    }

    private void writeToExcel(String path, List<LastPassResult> results) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Translate Result");
        setTitle(sheet);
        for (int i = 0; i < results.size(); i++) {
            LastPassResult result = results.get(i);
            Row row = sheet.createRow(i + 1);
            Cell countryCode = row.createCell(0);
            countryCode.setCellValue(result.getCountryCode());
            Cell originalText = row.createCell(1);
            originalText.setCellValue(result.getOriginalText());
            Cell comparedText = row.createCell(2);
            comparedText.setCellValue(result.getCompareText());
            Cell detectResult = row.createCell(3);
            detectResult.setCellValue(result.getCodeResult());
            Cell codeRemark = row.createCell(4);
            codeRemark.setCellValue(result.getCodeRemark());
            Cell translatedText = row.createCell(5);
            translatedText.setCellValue(result.getTranslatedText());
            Cell translatedResult = row.createCell(6);
            translatedResult.setCellValue(result.getTranslateResult());
            Cell distance = row.createCell(7);
            distance.setCellValue(result.getDistance());
        }
        File file = new File(Environment.getExternalStorageDirectory(), "translateResult.xls");
        FileUtils.writeExcel(workbook, file);
    }

    private void setTitle(HSSFSheet sheet) {
        Row title = sheet.createRow(0);
        Cell countryCode = title.createCell(0);
        countryCode.setCellValue("CountryCode");
        Cell originalText = title.createCell(1);
        originalText.setCellValue("OriginalText");
        Cell comparedText = title.createCell(2);
        comparedText.setCellValue("ComparedText");
        Cell detectResult = title.createCell(3);
        detectResult.setCellValue("DetectResult(Pass/Fail)");
        Cell codeRemark = title.createCell(4);
        codeRemark.setCellValue("CodeRemark");
        Cell translatedText = title.createCell(5);
        translatedText.setCellValue("TranslatedText");
        Cell translatedResult = title.createCell(6);
        translatedResult.setCellValue("TranslatedResult(Pass/Fail)");
        Cell distance = title.createCell(7);
        distance.setCellValue("Distance");
    }

    private class TranslateTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            output.setText("翻译开始...");
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                results = readFailExcel("");
                results = translateByGoogle(results);
                writeToExcel("", results);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String s) {
            output.setText("翻译完成");
        }
    }


}
